package com.ruoyi.system.service.impl;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.FeedbackMapper;
import com.ruoyi.system.utils.DifyApiUtil;
import com.ruoyi.system.vo.DifyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.DifyAppMapper;
import com.ruoyi.system.service.IDifyAppService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * Dify应用配置Service业务层处理
 * 
 * @author xiaoyilala
 * @date 2025-07-23
 */
@Service
@Slf4j
public class DifyAppServiceImpl implements IDifyAppService 
{

    @Value("${dify.api.baseUrl}")
    private String difyBaseUrl;

    @Value("${dify.api.redirectUrl}")
    private String redirectUrl;
    @Autowired
    private DifyAppMapper difyAppMapper;

    @Autowired
    private FeedbackMapper feedbackMapper;

    /**
     * 查询Dify应用配置
     * 
     * @param id Dify应用配置主键
     * @return Dify应用配置
     */
    @Override
    public DifyApp selectDifyAppById(Long id)
    {
        return difyAppMapper.selectDifyAppById(id);
    }

    /**
     * 查询Dify应用配置列表
     * 
     * @param difyApp Dify应用配置
     * @return Dify应用配置
     */
    @Override
    public List<DifyApp> selectDifyAppList(DifyApp difyApp)
    {
        return difyAppMapper.selectDifyAppList(difyApp);
    }

    /**
     * 新增Dify应用配置
     * 
     * @param difyApp Dify应用配置
     * @return 结果
     */
    @Override
    public int insertDifyApp(DifyApp difyApp)
    {
        difyApp.setCreateTime(DateUtils.getNowDate());
        return difyAppMapper.insertDifyApp(difyApp);
    }

    /**
     * 修改Dify应用配置
     * 
     * @param difyApp Dify应用配置
     * @return 结果
     */
    @Override
    public int updateDifyApp(DifyApp difyApp)
    {
        difyApp.setUpdateTime(DateUtils.getNowDate());
        return difyAppMapper.updateDifyApp(difyApp);
    }

    /**
     * 批量删除Dify应用配置
     * 
     * @param ids 需要删除的Dify应用配置主键
     * @return 结果
     */
    @Override
    public int deleteDifyAppByIds(Long[] ids)
    {
        return difyAppMapper.deleteDifyAppByIds(ids);
    }

    /**
     * 删除Dify应用配置信息
     * 
     * @param id Dify应用配置主键
     * @return 结果
     */
    @Override
    public int deleteDifyAppById(Long id)
    {
        return difyAppMapper.deleteDifyAppById(id);
    }

    @Override
    public List<DifyVO> selectDifyList() {
        List<DifyApp> difyApps =  difyAppMapper.selectList();
        if (difyApps==null){
            return null;
        }
        List<DifyVO> difyVOS = difyApps.stream().map(w->{
            DifyVO difyVO = new DifyVO();
            BeanUtils.copyProperties(w,difyVO);
            Optional<DifySiteInfo> difySiteInfoOptional = DifyApiUtil.getSiteInfo(difyBaseUrl, w.getAppKey());
            if (difySiteInfoOptional.isPresent()){
                DifySiteInfo difySiteInfo = difySiteInfoOptional.get();
                difyVO.setDifySiteInfo(difySiteInfo);
            }

//            try {
//                String path = new java.net.URL(difyVO.getDifyUrl()).getPath();
//                path = redirectUrl + path;
//                difyVO.setDifyUrl(path);
//            } catch (MalformedURLException e) {
//                throw new RuntimeException(e);
//            }
            return difyVO;
        }).collect(Collectors.toList());
        return difyVOS;
    }

    @Override
    public int addDifyApp(DifyApp difyApp) {
        Optional<DifyAppInfo> appInfoOptional = DifyApiUtil.getAppInfo(difyBaseUrl, difyApp.getAppKey());
        if (appInfoOptional.isPresent()){
            DifyAppInfo difyAppInfo = appInfoOptional.get();
            difyApp.setAppName(difyAppInfo.getName());
            difyApp.setDescription(difyAppInfo.getDescription());
        }
        Optional<DifySiteInfo> difySiteInfoOptional = DifyApiUtil.getSiteInfo(difyBaseUrl, difyApp.getAppKey());
        if (difySiteInfoOptional.isPresent()){
           DifySiteInfo difySiteInfo = difySiteInfoOptional.get();
           if (difySiteInfo.getIconUrl()!=null){
               difyApp.setIconUrl(difySiteInfo.getIconUrl());
           }
        }
        return difyAppMapper.insertDifyApp(difyApp);
    }

    @Override
    @Transactional
    @Scheduled(cron = "0 */1 * * * ?")
    public void getDifyInfo() {
        log.debug("定时任务开始执行！！！！！！！！！！！！！！！");
        List<DifyApp> difyApps  = difyAppMapper.selectAllList();
        difyApps.forEach(w->{
            Optional<DifyAppInfo> appInfoOptional = DifyApiUtil.getAppInfo(difyBaseUrl, w.getAppKey());
            if (appInfoOptional.isPresent()){
                DifyAppInfo difyAppInfo = appInfoOptional.get();
                log.debug("赋值得到的信息：{}",difyAppInfo);
                w.setAppName(difyAppInfo.getName());
                w.setDescription(difyAppInfo.getDescription());
            }
            Optional<DifySiteInfo> difySiteInfoOptional = DifyApiUtil.getSiteInfo(difyBaseUrl, w.getAppKey());
            if (difySiteInfoOptional.isPresent()){
                DifySiteInfo difySiteInfo = difySiteInfoOptional.get();
                if (difySiteInfo.getIconUrl()!=null && !difySiteInfo.getIconUrl().isEmpty()){
                    w.setIconUrl(difySiteInfo.getIconUrl());
                }
            }
            log.debug("当前difyapp信息：{}",w);
            difyAppMapper.updateDifyApp(w);
        });
    }

    @Override
    public void feedback(FeedbackReq feedbackReq) {
        FeedbackDO feedbackDO = new FeedbackDO();
        BeanUtils.copyProperties(feedbackReq,feedbackDO);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        feedbackDO.setUserId(sysUser.getThirdPartyUserId());
        feedbackMapper.insert(feedbackDO);
    }

    @Override
    public List<FeedbackDO> getFeedback() {
        return feedbackMapper.selectList();
    }
}
